package handler

import (
	"context"
	"coroutine/server/basic/config"
	"coroutine/server/basic/model"
	"coroutine/server/pkg"
	pb "coroutine/server/proto"
)

type Server struct {
	*pb.UnimplementedUserServer
}

func (s *Server) CreateUser(_ context.Context, in *pb.CreateUserReq) (*pb.CreateUserResp, error) {
	var u model.User
	config.DB.Debug().Where("name = ?", in.Name).Limit(1).Find(&u)
	if u.Id != 0 {
		return &pb.CreateUserResp{
			Message: "该账号已注册",
			Code:    10001,
		}, nil
	}
	user := model.User{
		Name:     in.Name,
		Password: pkg.Md5(in.Password),
	}
	err := config.DB.Debug().Create(&user).Error
	if err != nil {
		return &pb.CreateUserResp{
			Message: "注册失败",
			Code:    10002,
		}, nil
	}
	return &pb.CreateUserResp{
		Message: "注册成功",
		Code:    200,
	}, nil
}
func (s *Server) LoginUser(_ context.Context, in *pb.LoginUserReq) (*pb.LoginUserResp, error) {
	var u model.User
	config.DB.Debug().Where("name = ?", in.Name).Limit(1).Find(&u)
	if u.Id == 0 {
		return &pb.LoginUserResp{
			Message: "该账号未注册",
			Code:    10001,
		}, nil
	}
	if u.Password != pkg.Md5(in.Password) {
		return &pb.LoginUserResp{
			Message: "密码错误",
			Code:    10002,
		}, nil
	}
	return &pb.LoginUserResp{
		Message: "登录成功",
		Code:    200,
		Uid:     u.Id,
	}, nil
}
func (s *Server) UpdateUser(_ context.Context, in *pb.UpdateUserReq) (*pb.UpdateUserResp, error) {
	var u model.User
	config.DB.Debug().Where("id = ?", in.Uid).Limit(1).Find(&u)
	if u.Id == 0 {
		return &pb.UpdateUserResp{
			Message: "未登录",
			Code:    10001,
		}, nil
	}
	user := model.User{
		Id:       u.Id,
		FullName: in.FullName,
		CardType: in.CardType,
		UIdCard:  in.UIdCard,
	}
	err := config.DB.Debug().Updates(&user).Error
	if err != nil {
		return &pb.UpdateUserResp{
			Message: "实名失败",
			Code:    10002,
		}, nil
	}
	return &pb.UpdateUserResp{
		Message: "实名成功",
		Code:    200,
	}, nil
}
